package org.rency.common.utils.tool;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

public class URLUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(URLUtils.class);

	/**
	 * 获取URL完整地址
	 * </br>Created on 2016年2月23日
	 * @param href
	 * @param host
	 * @param isAvailability 是否验证URL的有效性
	 * @return
	 */
	public static String getFillUrl(String href,String host,boolean isAvailability){
		Assert.notNull(host, "域名不能为空");
		href = formatUrl(href);
		if(StringUtils.isBlank(href)){
			return href;
		}
		
		if(host.endsWith("/")){
			host = host.substring(0, host.length() - 1);
		}
		if(href.indexOf(host) == -1){
			href = href.indexOf(host) != -1 ? href:host + href;
		}
		if(isAvailability && !isAvailability(href,2000)){
			return "";
		}
		return href;
	}
	
	public static String formatUrl(String href){
		if(StringUtils.isBlank(href)){
			return "";
		}
		if(href.toLowerCase().startsWith("javascript:") || href.toLowerCase().startsWith("mailto:") || href.toLowerCase().startsWith("#") || (href.startsWith("/") && href.length() == 1) ){
			return "";
		}
		
		if(href.startsWith("/")){
			while(true){
				href = href.substring(1,href.length());
				if(!href.startsWith("/")){
					break;
				}
			}
		}
		
		Matcher matcher = Pattern.compile("((https|http|ftp|rtsp|mms)?://)").matcher(href);
		if(!matcher.find()){
			href = "http://"+href;
		}
		
		if(href.endsWith("/") || href.endsWith("#")){
			href = href.substring(0,href.length() - 1);
		}
		return href;
	}
	
	public static String getHost(String url){
		try {
			if(StringUtils.isBlank(url)){
				return "";
			}
			if(url.toLowerCase().startsWith("javascript:") || url.toLowerCase().startsWith("mailto:") || url.toLowerCase().startsWith("#")){
				return "";
			}
			URL uri = new URL(url);
			String protocol = uri.getProtocol()+"://";
			String host = uri.getHost();
			return host.startsWith(protocol) ? host : protocol+host;
		} catch (MalformedURLException e) {
			return "";
		}
	}

	/**
	 * 判断URL是否有效
	 * </br>Created on 2016年2月23日
	 * @param url
	 * @param timeout 连接超时时间
	 * @return
	 */
	public static boolean isAvailability(String url,Integer timeout){
		if(timeout == 0){
			timeout = 2000;
		}
		try{
			URL u = new URL (url);
			HttpURLConnection conn =  ( HttpURLConnection )  u.openConnection (); 
			conn.setRequestMethod ("HEAD"); 
			conn.setConnectTimeout(timeout);
			conn.setDoInput(true);
			conn.setDoOutput(false);
			conn.setReadTimeout(timeout);
			conn.setAllowUserInteraction(false);
			conn.setInstanceFollowRedirects(false);
			conn.connect () ; 
			return conn.getResponseCode() == HttpURLConnection.HTTP_OK;
		}catch(Exception e){
			logger.warn("URL地址不可用[{}].{}",url,e.getMessage());
			return false;
		}
	}
	
	/**
	 * 判断是否达到目标深度
	 * </br>Created on 2016年2月23日
	 * @param url
	 * @param depth 深度
	 * @return
	 */
	public static boolean isAchieveDepth(String url,Integer depth){
		if(StringUtils.isBlank(url)){
			return true;
		}
		
		if(url.toLowerCase().startsWith("javascript:") || url.toLowerCase().startsWith("mailto:") || url.toLowerCase().startsWith("#") || url.toLowerCase().startsWith(url+"#") || (url.startsWith("/") && url.length() == 1) ){
			return true;
		}
		
		Matcher matcher = Pattern.compile("((https|http|ftp|rtsp|mms)?://)").matcher(url);
		if(matcher.find()){
			matcher.replaceFirst("");
		}
		
		if(url.indexOf("?") != -1){
			url = url.substring(0, url.indexOf("?") -1);
		}
		
		String[] sections = url.split("/");
		return sections.length > depth;
	}
}